<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use app\common\library\Withdraw as WithdrawService;

/**
 * 提现管理
 */
class Withdraw extends Backend
{
    protected $model = null;
    
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Withdraw;
    }
    
    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
                
            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
                
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    
    /**
     * 审核通过
     */
    public function approve($ids)
    {
        if(!$ids){
            $this->error('参数错误');
        }
        
        $withdraw = $this->model->where('status', 'created')->find($ids);
        if(!$withdraw){
            $this->error('提现记录不存在或已处理');
        }
        
        Db::startTrans();
        try {
            // 获取用户openid
            $user = \app\common\model\User::get($withdraw->user_id);
            if($withdraw->type == 'wechat' && empty($user->openid)) {
                $this->error('用户未绑定微信账号');
            }
            
            // 调用对应的提现接口
            if($withdraw->type == 'wechat') {
                $result = WithdrawService::wechat(
                    $user->openid,  // 使用用户的openid
                    $withdraw->out_biz_no,
                    $withdraw->money,
                    $withdraw->real_name,
                    '提现打款'
                );
            } else {
                $result = WithdrawService::alipay(
                    $withdraw->account,
                    $withdraw->out_biz_no,
                    $withdraw->money,
                    $withdraw->real_name,
                    '提现打款'
                );
            }
            if($result['status']){
                // 更新提现状态
                $withdraw->status = $result['state'];
                $withdraw->package_info = $result['package_info'];
                $withdraw->updatetime = time();
                $withdraw->payment_no = $result['payment_no'];
                $withdraw->save();

                // 记录消费日志
                Db::name('user_consume_log')->insert([
                    'user_id' => $withdraw->user_id,
                    'type' => 'withdraw',
                    'target_id' => $withdraw->id,
                    'target_title' => '提现',
                    'amount' => -$withdraw->money,
                    'createtime' => time()
                ]);
            } else {
                $this->error($result['msg']);
            }
            
            Db::commit();
            $this->success('打款成功');
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    
    /**
     * 驳回
     */
    public function reject($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if(!$params['ids'] || !$params['reason']){
                $this->error('参数错误');
            }
            
            $withdraw = $this->model->where('status', 'created')->find($params['ids']);
            if(!$withdraw){
                $this->error('提现记录不存在或已处理');
            }
            
            Db::startTrans();
            try {
                // 更新提现状态
                $withdraw->status = 'rejected';
                $withdraw->reason = $params['reason'];
                $withdraw->updatetime = time();
                $withdraw->save();
                
                // 退还余额
                $user = \app\common\model\User::get($withdraw->user_id);
                $user->setInc('money', $withdraw->money);
                
                // 添加余额变动记录
                Db::name('user_money_log')->insert([
                    'user_id' => $withdraw->user_id,
                    'money' => $withdraw->money,
                    'before' => $user->money - $withdraw->money,
                    'after' => $user->money,
                    'memo' => '提现驳回退款',
                    'createtime' => time()
                ]);
                
                Db::commit();
                $this->success('驳回成功');
            } catch (\think\exception\PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $this->view->assign("ids", $ids);
        return $this->view->fetch();
    }
    
}